@using Blazorise.Extensions;
@typeparam TItem
@{
    @if ( Column is DataGridNumericColumn<TItem> numericColumn )
    {
        <_DataGridCellNumericEdit Column="@numericColumn" CellValue="@GetSearchValue()" CellValueChanged="@FilterChanged" />
    }
    else if ( Column is DataGridSelectColumn<TItem> selectColumn )
    {
        <_DataGridCellSelectEdit Column="@selectColumn" CellValue="@GetSearchValue()" CellValueChanged="@FilterChanged" CellSection="DataGridCellSection.Filter" />
    }
    else if ( Column is DataGridCheckColumn<TItem> checkColumn )
    {
        <_DataGridCellCheckEdit Column="@checkColumn" CellValue="@GetSearchValue()" CellValueChanged="@FilterChanged" />
    }
    else if ( Column is DataGridDateColumn<TItem> dateColumn )
    {
        <_DataGridCellDatePicker Column="@dateColumn" CellValue="@GetSearchValue()" CellValueChanged="@FilterChanged" />
    }
    else
    {
        <TextEdit Text="@GetSearchValueAsString()" TextChanged="@(( newValue ) => FilterChanged( newValue ))" />
    }
}
@code {
    [Parameter] public DataGridColumn<TItem> Column { get; set; }

    [Parameter] public EventCallback<object> OnFilterChanged { get; set; }

    /// <summary>
    /// Workaround for an issue with the DatePicker setting the value to null if we try to set FilterValue as a Parameter.
    /// </summary>
    [Parameter] public DataGridCellFilterType CellFilterType { get; set; } = DataGridCellFilterType.Single;

    private Task FilterChanged( object newValue )
    {
        return OnFilterChanged.InvokeAsync( newValue );
    }

    private string GetSearchValueAsString()
    {
        if ( CellFilterType == DataGridCellFilterType.Single )
        {
            return Column.Filter.SearchValue?.ToString();
        }
        else if ( CellFilterType == DataGridCellFilterType.RangeFrom )
        {
            return GetFilterValue1()?.ToString();
        }
        else if ( CellFilterType == DataGridCellFilterType.RangeTo )
        {
            return GetFilterValue2()?.ToString();
        }
        return default;
    }

    private object GetSearchValue()
    {
        if ( CellFilterType == DataGridCellFilterType.Single )
        {
            return Column.Filter.SearchValue;
        }
        else if ( CellFilterType == DataGridCellFilterType.RangeFrom )
        {
            return GetFilterValue1();
        }
        else if ( CellFilterType == DataGridCellFilterType.RangeTo )
        {
            return GetFilterValue2();
        }
        return default;
    }

    private object GetFilterValue1()
    {
        return ( Column.Filter.SearchValue as object[] )?[0];
    }

    private object GetFilterValue2()
    {
        return ( Column.Filter.SearchValue as object[] )?[1];
    }
}